{% extends "admin/layout.html" %}

{% block title %}
    {% if asset %}编辑资产{% else %}新增资产{% endif %} - {{ system_config.site_name|default('项目管理系统') }}
{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0">
                    {% if asset %}编辑资产{% else %}新增资产{% endif %}
                </h1>

            </div>
            <a href="{{ url_for('asset.asset_list') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i> 返回列表
            </a>
        </div>

        <div class="row">
            <div class="col-lg-12">
                <!-- 统一使用一个表单 -->
                <form method="post" id="assetForm" novalidate>
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

                    <div class="row">
                        <div class="col-lg-8">
                            <!-- 基本信息卡片 -->
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-info-circle me-2"></i>基本信息
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="name" class="form-label">资产名称 <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="name" name="name"
                                                   value="{{ form_data.name if form_data else (asset.name if asset else '') }}"
                                                   required maxlength="200">
                                            <div class="invalid-feedback">请输入资产名称</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="asset_number" class="form-label">资产编号 <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="asset_number" name="asset_number"
                                                   value="{{ form_data.asset_number if form_data else (asset.asset_number if asset else '') }}"
                                                   required maxlength="100">
                                            <div class="form-text">唯一标识，不可重复</div>
                                            <div class="invalid-feedback">请输入资产编号</div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="category_id" class="form-label">资产类别 <span class="text-danger">*</span></label>
                                            <select class="form-select" id="category_id" name="category_id" required onchange="loadCustomFields(this.value)">
                                                <option value="">请选择类别</option>
                                                {% for category in categories %}
                                                    <option value="{{ category.id }}"
                                                            {% if form_data and form_data.category_id|int == category.id %}selected{% elif asset and asset.category_id == category.id %}selected{% endif %}>
                                                        {{ category.name }}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                            <div class="invalid-feedback">请选择资产类别</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="serial_number" class="form-label">序列号</label>
                                            <input type="text" class="form-control" id="serial_number" name="serial_number"
                                                   value="{{ form_data.serial_number if form_data else (asset.serial_number if asset else '') }}" maxlength="100">
                                            <div class="form-text">设备的唯一序列号</div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="model" class="form-label">型号</label>
                                            <input type="text" class="form-control" id="model" name="model"
                                                   value="{{ form_data.model if form_data else (asset.model if asset else '') }}" maxlength="200">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="brand" class="form-label">品牌</label>
                                            <input type="text" class="form-control" id="brand" name="brand"
                                                   value="{{ form_data.brand if form_data else (asset.brand if asset else '') }}" maxlength="100">
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label for="supplier_ids" class="form-label">供应商</label>
                                        <select class="form-select" id="supplier_ids" name="supplier_ids" multiple size="3">
                                            {% for supplier in suppliers %}
                                                <option value="{{ supplier.id }}"
                                                        {% if form_data and supplier.id|string in form_data.supplier_ids %}selected{% elif asset and supplier in asset.suppliers %}selected{% endif %}>
                                                    {{ supplier.name }}
                                                </option>
                                            {% endfor %}
                                        </select>
                                        <div class="form-text">可多选，按住Ctrl键选择多个供应商</div>
                                    </div>

                                    <div class="mb-3">
                                        <label for="description" class="form-label">资产描述</label>
                                        <textarea class="form-control" id="description" name="description" rows="3" maxlength="500">{{ form_data.description if form_data else (asset.description if asset else '') }}</textarea>
                                        <div class="form-text">最多500个字符</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 财务信息卡片 -->
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-money-bill-wave me-2"></i>财务信息
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label for="purchase_price" class="form-label">购买价格</label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" id="purchase_price" name="purchase_price"
                                                       step="0.01" min="0" value="{{ form_data.purchase_price if form_data else (asset.purchase_price if asset and asset.purchase_price else '') }}" oninput="validateNumber(this)">
                                            </div>
                                            <div class="invalid-feedback">请输入有效的价格</div>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="purchase_date" class="form-label">购买日期</label>
                                            <input type="date" class="form-control" id="purchase_date" name="purchase_date"
                                                   value="{{ form_data.purchase_date if form_data else (asset.purchase_date.strftime('%Y-%m-%d') if asset and asset.purchase_date else '') }}">
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="warranty_months" class="form-label">保修月数</label>
                                            <input type="number" class="form-control" id="warranty_months" name="warranty_months"
                                                   min="0" value="{{ form_data.warranty_months if form_data else (asset.warranty_months if asset and asset.warranty_months else '') }}">
                                            <div class="invalid-feedback">请输入有效的保修月数</div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="depreciation_rate" class="form-label">折旧率 (%)</label>
                                            <input type="number" class="form-control" id="depreciation_rate" name="depreciation_rate"
                                                   step="0.01" min="0" max="100" value="{{ form_data.depreciation_rate if form_data else (asset.depreciation_rate if asset and asset.depreciation_rate else '') }}" oninput="validateNumber(this)">
                                            <div class="form-text">每年折旧的百分比</div>
                                            <div class="invalid-feedback">请输入0-100之间的数值</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="form-text pt-4">
                                                {% if asset and asset.purchase_date and asset.warranty_months %}
                                                    <strong>保修截止日期:</strong>
                                                    {{ asset.warranty_expiry.strftime('%Y-%m-%d') if asset.warranty_expiry else '未计算' }}
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 硬件信息卡片 -->
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-microchip me-2"></i>硬件信息
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="cpu_info" class="form-label">CPU信息</label>
                                            <textarea class="form-control" id="cpu_info" name="cpu_info" rows="2"
                                                      placeholder="CPU型号、核心数、频率等">{{ form_data.cpu_info if form_data else (asset.cpu_info if asset else '') }}</textarea>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="memory_info" class="form-label">内存信息</label>
                                            <textarea class="form-control" id="memory_info" name="memory_info" rows="2"
                                                      placeholder="内存大小、类型、配置等">{{ form_data.memory_info if form_data else (asset.memory_info if asset else '') }}</textarea>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="disk_info" class="form-label">磁盘信息</label>
                                            <textarea class="form-control" id="disk_info" name="disk_info" rows="2"
                                                      placeholder="硬盘容量、类型、数量等">{{ form_data.disk_info if form_data else (asset.disk_info if asset else '') }}</textarea>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="os_info" class="form-label">操作系统</label>
                                            <input type="text" class="form-control" id="os_info" name="os_info"
                                                   value="{{ form_data.os_info if form_data else (asset.os_info if asset else '') }}"
                                                   placeholder="操作系统名称和版本">
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label for="network_info" class="form-label">网络信息</label>
                                        <textarea class="form-control" id="network_info" name="network_info" rows="2"
                                                  placeholder="IP地址、MAC地址、网络接口等">{{ form_data.network_info if form_data else (asset.network_info if asset else '') }}</textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label for="specifications" class="form-label">完整规格信息(JSON)</label>
                                        <textarea class="form-control" id="specifications" name="specifications" rows="4"
                                                  placeholder='{"hardware_info": {...}, "system_info": {...}}'>{{ form_data.specifications if form_data else (asset.specifications if asset else '') }}</textarea>
                                        <div class="form-text">自动发现资产会填充此字段，也可手动编辑</div>
                                    </div>
                                </div>
                            </div>
                            <!-- 自定义字段区域 -->
                            <div class="card mb-4" id="customFieldsSection" style="display: none;">
                                <div class="card-header bg-light">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-tags me-2"></i>自定义属性
                                    </h5>
                                </div>
                                <div class="card-body" id="customFieldsContainer">
                                    <!-- 动态加载的自定义字段将显示在这里 -->
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <!-- 使用信息卡片 -->
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-user-check me-2"></i>使用信息
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="status" class="form-label">状态</label>
                                        <select class="form-select" id="status" name="status">
                                            <option value="draft" {% if form_data and form_data.status == 'draft' %}selected{% elif asset and asset.status == 'draft' %}selected{% endif %}>草稿</option>
                                            <option value="pending" {% if form_data and form_data.status == 'pending' %}selected{% elif asset and asset.status == 'pending' %}selected{% endif %}>待确认</option>
                                            <option value="available" {% if form_data and form_data.status == 'available' %}selected{% elif asset and asset.status == 'available' %}selected{% endif %}>可用</option>
                                            <option value="in_use" {% if form_data and form_data.status == 'in_use' %}selected{% elif asset and asset.status == 'in_use' %}selected{% endif %}>使用中</option>
                                            <option value="maintenance" {% if form_data and form_data.status == 'maintenance' %}selected{% elif asset and asset.status == 'maintenance' %}selected{% endif %}>维护中</option>
                                            <option value="reserved" {% if form_data and form_data.status == 'reserved' %}selected{% elif asset and asset.status == 'reserved' %}selected{% endif %}>预留</option>
                                            <option value="retired" {% if form_data and form_data.status == 'retired' %}selected{% elif asset and asset.status == 'retired' %}selected{% endif %}>已报废</option>
                                            <option value="lost" {% if form_data and form_data.status == 'lost' %}selected{% elif asset and asset.status == 'lost' %}selected{% endif %}>丢失</option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="assigned_to_id" class="form-label">使用人</label>
                                        <select class="form-select" id="assigned_to_id" name="assigned_to_id">
                                            <option value="">未分配</option>
                                            {% for member in members %}
                                                <option value="{{ member.id }}"
                                                        {% if form_data and form_data.assigned_to_id|int == member.id %}selected{% elif asset and asset.assigned_to_id == member.id %}selected{% endif %}>
                                                    {{ member.name }} {% if member.department %}({{ member.department.name }}){% endif %}
                                                </option>
                                            {% endfor %}
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="location" class="form-label">存放位置</label>
                                        <input type="text" class="form-control" id="location" name="location"
                                               value="{{ form_data.location if form_data else (asset.location if asset else '') }}" maxlength="200">
                                    </div>

                                    <div class="mb-3">
                                        <label for="notes" class="form-label">备注</label>
                                        <textarea class="form-control" id="notes" name="notes" rows="3" maxlength="1000">{{ form_data.notes if form_data else (asset.notes if asset else '') }}</textarea>
                                        <div class="form-text">最多1000个字符</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 系统信息卡片 -->
                            {% if asset %}
                                <div class="card mb-4">
                                    <div class="card-header bg-light">
                                        <h5 class="card-title mb-0">
                                            <i class="fas fa-cog me-2"></i>系统信息
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-2">
                                            <small class="text-muted">创建时间:</small>
                                            <div>{{ asset.created_at.strftime('%Y-%m-%d %H:%M') if asset.created_at else '未知' }}</div>
                                        </div>
                                        <div class="mb-2">
                                            <small class="text-muted">最后更新:</small>
                                            <div>{{ asset.updated_at.strftime('%Y-%m-%d %H:%M') if asset.updated_at else '未知' }}</div>
                                        </div>
                                        {% if asset.auto_discovered %}
                                            <div class="mb-2">
                                                <small class="text-muted">发现方式:</small>
                                                <div class="badge bg-info">自动发现</div>
                                            </div>
                                        {% endif %}
                                        {% if asset.confirmation_status %}
                                            <div class="mb-2">
                                                <small class="text-muted">确认状态:</small>
                                                <div class="badge {% if asset.confirmation_status == 'confirmed' %}bg-success{% elif asset.confirmation_status == 'rejected' %}bg-danger{% else %}bg-warning{% endif %}">
                                                    {{ asset.confirmation_status_label }}
                                                </div>
                                            </div>
                                        {% endif %}
                                    </div>
                                </div>
                            {% endif %}

                            <!-- 操作按钮卡片 -->
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save me-1"></i>
                                            {% if asset %}更新资产{% else %}创建资产{% endif %}
                                        </button>
                                        <a href="{{ url_for('asset.asset_list') }}" class="btn btn-outline-secondary">
                                            <i class="fas fa-times me-1"></i>取消
                                        </a>
                                    </div>
                                    {% if asset %}
                                        <hr>
                                        <div class="d-grid">
                                            <a href="{{ url_for('asset.asset_detail', asset_id=asset.id) }}" class="btn btn-outline-info">
                                                <i class="fas fa-eye me-1"></i>查看详情
                                            </a>
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 表单验证和字段处理
        document.addEventListener('DOMContentLoaded', function() {
            // 页面加载时，如果有选中的类别，加载自定义字段
            const categorySelect = document.getElementById('category_id');
            if (categorySelect.value) {
                loadCustomFields(categorySelect.value);
            }

            // 表单提交验证
            const form = document.getElementById('assetForm');
            form.addEventListener('submit', function(e) {
                if (!form.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }

                // 处理空数值字段
                const price = document.getElementById('purchase_price');
                const rate = document.getElementById('depreciation_rate');
                const warranty = document.getElementById('warranty_months');

                if (price.value === '') price.value = '';
                if (rate.value === '') rate.value = '';
                if (warranty.value === '') warranty.value = '';

                form.classList.add('was-validated');
            });

            // 实时验证
            const inputs = form.querySelectorAll('input, select, textarea');
            inputs.forEach(input => {
                input.addEventListener('blur', function() {
                    this.classList.add('validated');
                    validateField(this);
                });

                input.addEventListener('input', function() {
                    if (this.classList.contains('validated')) {
                        validateField(this);
                    }
                });
            });
        });

        function validateNumber(input) {
            // 如果输入为空，清空值
            if (input.value === '') {
                input.value = '';
                return;
            }

            // 确保数值在合理范围内
            if (input.value < 0) {
                input.value = 0;
            }
            if (input.id === 'depreciation_rate' && input.value > 100) {
                input.value = 100;
            }

            // 验证字段
            validateField(input);
        }

        function validateField(field) {
            if (field.checkValidity()) {
                field.classList.remove('is-invalid');
                field.classList.add('is-valid');
            } else {
                field.classList.remove('is-valid');
                field.classList.add('is-invalid');
            }
        }

        // 自定义字段处理
        function loadCustomFields(categoryId) {
            if (!categoryId) {
                document.getElementById('customFieldsSection').style.display = 'none';
                return;
            }

            // 显示加载状态
            const container = document.getElementById('customFieldsContainer');
            container.innerHTML = '<div class="text-center py-3"><i class="fas fa-spinner fa-spin me-2"></i>加载中...</div>';

            fetch(`/admin/asset/api/assets/custom-fields/${categoryId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    const section = document.getElementById('customFieldsSection');

                    if (data.custom_fields && data.custom_fields.length > 0) {
                        container.innerHTML = '';
                        data.custom_fields.forEach(field => {
                            const fieldHtml = createCustomFieldHtml(field);
                            container.innerHTML += fieldHtml;
                        });
                        section.style.display = 'block';

                        // 填充已有数据（编辑模式下）
                        {% if asset and asset.attributes %}
                            const assetAttributes = {
                                {% for attr in asset.attributes %}
                                    {{ attr.field_id }}: "{{ attr.attribute_value }}",
                                {% endfor %}
                            };

                            data.custom_fields.forEach(field => {
                                if (assetAttributes[field.id]) {
                                    const fieldElement = document.getElementById(`custom_field_${field.id}`);
                                    if (fieldElement) {
                                        if (field.field_type === 'boolean') {
                                            fieldElement.checked = (assetAttributes[field.id] === 'true');
                                        } else {
                                            fieldElement.value = assetAttributes[field.id];
                                        }
                                    }
                                }
                            });
                        {% endif %}
                    } else {
                        container.innerHTML = '<div class="text-center py-3 text-muted">暂无自定义字段</div>';
                        section.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('加载自定义字段失败:', error);
                    container.innerHTML = '<div class="alert alert-warning">加载自定义字段失败，请刷新页面重试</div>';
                });
        }

        function createCustomFieldHtml(field) {
            const fieldId = `custom_field_${field.id}`;
            let fieldHtml = `
        <div class="mb-3">
            <label for="${fieldId}" class="form-label">${field.name} ${field.is_required ? '<span class="text-danger">*</span>' : ''}</label>
    `;

            // 获取字段的当前值（编辑模式下）
            let currentValue = '';
            {% if asset %}
                {% for attr in asset.attributes %}
                    {% if attr.field_id == field.id %}
                        currentValue = "{{ attr.attribute_value }}";
                    {% endif %}
                {% endfor %}
            {% endif %}

            switch(field.field_type) {
                case 'text':
                    fieldHtml += `<input type="text" class="form-control" id="${fieldId}" name="custom_field_${field.id}"
                           ${field.is_required ? 'required' : ''} value="${currentValue}">`;
                    break;
                case 'number':
                    fieldHtml += `<input type="number" class="form-control" id="${fieldId}" name="custom_field_${field.id}"
                           ${field.is_required ? 'required' : ''} value="${currentValue}">`;
                    break;
                case 'date':
                    fieldHtml += `<input type="date" class="form-control" id="${fieldId}" name="custom_field_${field.id}"
                           ${field.is_required ? 'required' : ''} value="${currentValue}">`;
                    break;
                case 'select':
                    fieldHtml += `<select class="form-select" id="${fieldId}" name="custom_field_${field.id}" ${field.is_required ? 'required' : ''}>
                <option value="">请选择</option>`;
                    field.options.forEach(option => {
                        const selected = (option === currentValue) ? 'selected' : '';
                        fieldHtml += `<option value="${option}" ${selected}>${option}</option>`;
                    });
                    fieldHtml += `</select>`;
                    break;
                case 'boolean':
                    const checked = (currentValue === 'true') ? 'checked' : '';
                    fieldHtml += `<div class="form-check">
                <input class="form-check-input" type="checkbox" id="${fieldId}" name="custom_field_${field.id}" value="true" ${checked}>
                <label class="form-check-label" for="${fieldId}">是</label>
            </div>`;
                    break;
                case 'textarea':
                    fieldHtml += `<textarea class="form-control" id="${fieldId}" name="custom_field_${field.id}" rows="3"
                           ${field.is_required ? 'required' : ''}>${currentValue}</textarea>`;
                    break;
                default:
                    fieldHtml += `<input type="text" class="form-control" id="${fieldId}" name="custom_field_${field.id}"
                           ${field.is_required ? 'required' : ''} value="${currentValue}">`;
            }

            fieldHtml += `</div>`;
            return fieldHtml;
        }

        // 购买日期和保修月数变化时自动计算保修截止日期
        document.addEventListener('DOMContentLoaded', function() {
            const purchaseDate = document.getElementById('purchase_date');
            const warrantyMonths = document.getElementById('warranty_months');

            function calculateWarrantyExpiry() {
                if (purchaseDate.value && warrantyMonths.value) {
                    const date = new Date(purchaseDate.value);
                    date.setMonth(date.getMonth() + parseInt(warrantyMonths.value));

                    // 更新显示（这里只是示例，实际应该更新到相应显示区域）
                    console.log('保修截止日期:', date.toISOString().split('T')[0]);
                }
            }

            if (purchaseDate) purchaseDate.addEventListener('change', calculateWarrantyExpiry);
            if (warrantyMonths) warrantyMonths.addEventListener('change', calculateWarrantyExpiry);
        });
    </script>

    <style>
        .form-control.validated:valid {
            border-color: #198754;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .form-control.validated:invalid {
            border-color: #dc3545;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .card-header.bg-light {
            background-color: #f8f9fa !important;
            border-bottom: 1px solid #dee2e6;
        }
    </style>
{% endblock %}